<template>
  <div class="dashboard-container">
    <el-scrollbar style="height: 100%">
      <div v-loading="loading" class="dashboard-content">
        <!-- 今日概况 -->
        <div class="section-title">今日概况</div>
        <div class="overview-container">
          <div class="overview-item">
            <div class="overview-label">单据数量</div>
            <div class="overview-value">{{ todayData.orderCount }}</div>
            <el-button type="success" size="small" class="action-btn">入库</el-button>
          </div>
          <div class="overview-item">
            <div class="overview-label">入库数量</div>
            <div class="overview-value">{{ todayData.inboundQuantity }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">入库金额</div>
            <div class="overview-value">{{ formatMoney(todayData.inboundAmount) }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">出库数量</div>
            <div class="overview-value">{{ todayData.outboundQuantity }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">出库金额</div>
            <div class="overview-value">{{ formatMoney(todayData.outboundAmount) }}</div>
            <el-button type="warning" size="small" class="action-btn">出库</el-button>
          </div>
        </div>

        <!-- 昨日概况 -->
        <div class="section-title">昨日概况</div>
        <div class="overview-container">
          <div class="overview-item">
            <div class="overview-label">单据数量</div>
            <div class="overview-value">{{ yesterdayData.orderCount }}</div>
            <el-button type="success" size="small" class="action-btn">入库</el-button>
          </div>
          <div class="overview-item">
            <div class="overview-label">入库数量</div>
            <div class="overview-value">{{ yesterdayData.inboundQuantity }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">入库金额</div>
            <div class="overview-value">{{ formatMoney(yesterdayData.inboundAmount) }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">出库数量</div>
            <div class="overview-value">{{ yesterdayData.outboundQuantity }}</div>
          </div>
          <div class="overview-item">
            <div class="overview-label">出库金额</div>
            <div class="overview-value">{{ formatMoney(yesterdayData.outboundAmount) }}</div>
            <el-button type="warning" size="small" class="action-btn">出库</el-button>
          </div>
        </div>

        <!-- 图表区域 -->
        <div class="charts-container">
          <!-- 库存数量占比 -->
          <div class="chart-box">
            <div class="chart-title">库存数量占比</div>
            <div id="quantityChart" class="chart"></div>
          </div>

          <!-- 库存金额占比 -->
          <div class="chart-box">
            <div class="chart-title">库存金额占比</div>
            <div id="amountChart" class="chart"></div>
          </div>
        </div>

        <!-- 入库统计 -->
        <div class="trend-section">
          <div class="trend-header">
            <div class="section-title" style="margin-bottom: 0;">入库统计</div>
            <div class="time-range-tabs">
              <el-radio-group v-model="inboundDays" size="small" @change="loadInboundTrend">
                <el-radio-button :value="7">最近7天</el-radio-button>
                <el-radio-button :value="30">最近30天</el-radio-button>
                <el-radio-button :value="365">最近一年</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-box">
            <div id="inboundTrendChart" class="trend-chart"></div>
          </div>
        </div>

        <!-- 出库统计 -->
        <div class="trend-section">
          <div class="trend-header">
            <div class="section-title" style="margin-bottom: 0;">出库统计</div>
            <div class="time-range-tabs">
              <el-radio-group v-model="outboundDays" size="small" @change="loadOutboundTrend">
                <el-radio-button :value="7">最近7天</el-radio-button>
                <el-radio-button :value="30">最近30天</el-radio-button>
                <el-radio-button :value="365">最近一年</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-box">
            <div id="outboundTrendChart" class="trend-chart"></div>
          </div>
        </div>

        <!-- 排名统计 -->
        <div class="ranking-container">
          <!-- 入库排名 -->
          <div class="ranking-box">
            <div class="section-title">入库排名</div>
            <div class="ranking-table-wrapper">
              <table class="ranking-table">
                <thead>
                  <tr>
                    <th width="80">排名</th>
                    <th>货品名称</th>
                    <th width="100">数量</th>
                    <th width="120">金额</th>
                    <th width="100">入库次数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in inboundRankingData" :key="item.rank">
                    <td>
                      <div class="rank-badge" :class="getRankClass(item.rank)">
                        {{ item.rank }}
                      </div>
                    </td>
                    <td class="goods-name">{{ item.goodsName }}</td>
                    <td class="text-right">{{ item.quantity }}</td>
                    <td class="text-right">{{ formatMoney(item.amount) }}</td>
                    <td class="text-center">{{ item.count }}</td>
                  </tr>
                  <tr v-if="inboundRankingData.length === 0">
                    <td colspan="5" class="empty-data">暂无数据</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- 出库排名 -->
          <div class="ranking-box">
            <div class="section-title">出库排名</div>
            <div class="ranking-table-wrapper">
              <table class="ranking-table">
                <thead>
                  <tr>
                    <th width="80">排名</th>
                    <th>货品名称</th>
                    <th width="100">数量</th>
                    <th width="120">金额</th>
                    <th width="100">出库次数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in outboundRankingData" :key="item.rank">
                    <td>
                      <div class="rank-badge" :class="getRankClass(item.rank)">
                        {{ item.rank }}
                      </div>
                    </td>
                    <td class="goods-name">{{ item.goodsName }}</td>
                    <td class="text-right">{{ item.quantity }}</td>
                    <td class="text-right">{{ formatMoney(item.amount) }}</td>
                    <td class="text-center">{{ item.count }}</td>
                  </tr>
                  <tr v-if="outboundRankingData.length === 0">
                    <td colspan="5" class="empty-data">暂无数据</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
    
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import * as echarts from 'echarts'
import http from '@/api/http'

const { proxy } = getCurrentInstance()

// 数据定义
const loading = ref(false)
const todayData = reactive({
  orderCount: 0,
  inboundQuantity: 0,
  inboundAmount: 0,
  outboundQuantity: 0,
  outboundAmount: 0
})

const yesterdayData = reactive({
  orderCount: 0,
  inboundQuantity: 0,
  inboundAmount: 0,
  outboundQuantity: 0,
  outboundAmount: 0
})

const inventoryQuantityData = ref([])
const inventoryAmountData = ref([])
const totalInventoryQuantity = ref(0)
const totalInventoryAmount = ref(0)

// 趋势图表数据
const inboundDays = ref(7)
const outboundDays = ref(7)
const inboundTrendData = ref({
  dates: [],
  quantities: [],
  amounts: [],
  totalQuantity: 0,
  totalAmount: 0
})
const outboundTrendData = ref({
  dates: [],
  quantities: [],
  amounts: [],
  totalQuantity: 0,
  totalAmount: 0
})

// 排名数据
const inboundRankingData = ref([])
const outboundRankingData = ref([])

let quantityChartInstance = null
let amountChartInstance = null
let inboundTrendChartInstance = null
let outboundTrendChartInstance = null
let refreshInterval = null

// 格式化金额
const formatMoney = (value) => {
  return value ? value.toFixed(2) : '0.00'
}

// 获取排名样式类
const getRankClass = (rank) => {
  if (rank === 1) return 'rank-first'
  if (rank === 2) return 'rank-second'
  if (rank === 3) return 'rank-third'
  return ''
}

// 获取大屏数据
const getDashboardData = async () => {
  try {
    loading.value = true
    const response = await http.get('api/Dashboard/GetDashboardData')
    
    if (response.success) {
      const data = response.data
      
      // 更新今日概况
      Object.assign(todayData, data.todayOverview)
      
      // 更新昨日概况
      Object.assign(yesterdayData, data.yesterdayOverview)
      
      // 更新库存数据
      inventoryQuantityData.value = data.inventoryQuantityByWarehouse || []
      inventoryAmountData.value = data.inventoryAmountByWarehouse || []
      totalInventoryQuantity.value = data.totalInventoryQuantity || 0
      totalInventoryAmount.value = data.totalInventoryAmount || 0
      
      // 渲染图表
      renderQuantityChart()
      renderAmountChart()
    } else {
      proxy.$message.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取大屏数据失败:', error)
    proxy.$message.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 渲染库存数量饼图
const renderQuantityChart = () => {
  if (!quantityChartInstance) {
    quantityChartInstance = echarts.init(document.getElementById('quantityChart'))
  }
  
  const option = {
    color: [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4'
    ],
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    title: {
      text: totalInventoryQuantity.value,
      subtext: '总库存',
      left: 'center',
      top: 'center',
      textStyle: {
        fontSize: 32,
        fontWeight: 'bold',
        color: '#333'
      },
      subtextStyle: {
        fontSize: 14,
        color: '#999'
      }
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: 'center',
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      formatter: (name) => {
        const item = inventoryQuantityData.value.find(d => d.warehouseName === name)
        return `${name}  ${item ? item.quantity : 0}`
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '60%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: inventoryQuantityData.value.map(item => ({
          name: item.warehouseName,
          value: item.quantity
        }))
      }
    ]
  }
  
  quantityChartInstance.setOption(option)
}

// 渲染库存金额饼图
const renderAmountChart = () => {
  if (!amountChartInstance) {
    amountChartInstance = echarts.init(document.getElementById('amountChart'))
  }
  
  const option = {
    color: [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4'
    ],
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    title: {
      text: formatMoney(totalInventoryAmount.value),
      subtext: '总金额',
      left: 'center',
      top: 'center',
      textStyle: {
        fontSize: 32,
        fontWeight: 'bold',
        color: '#333'
      },
      subtextStyle: {
        fontSize: 14,
        color: '#999'
      }
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: 'center',
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      formatter: (name) => {
        const item = inventoryAmountData.value.find(d => d.warehouseName === name)
        return `${name}  ${item ? formatMoney(item.amount) : '0.00'}`
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '60%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
            formatter: '{b}: ¥{c}'
          }
        },
        labelLine: {
          show: false
        },
        data: inventoryAmountData.value.map(item => ({
          name: item.warehouseName,
          value: item.amount
        }))
      }
    ]
  }
  
  amountChartInstance.setOption(option)
}

// 获取入库趋势数据
const loadInboundTrend = async () => {
  try {
    const response = await http.get('api/Dashboard/GetInboundTrendStats', { days: inboundDays.value })
    
    if (response.success) {
      inboundTrendData.value = response.data
      renderInboundTrendChart()
    } else {
      proxy.$message.error(response.message || '获取入库趋势数据失败')
    }
  } catch (error) {
    console.error('获取入库趋势数据失败:', error)
  }
}

// 获取出库趋势数据
const loadOutboundTrend = async () => {
  try {
    const response = await http.get('api/Dashboard/GetOutboundTrendStats', { days: outboundDays.value })
    
    if (response.success) {
      outboundTrendData.value = response.data
      renderOutboundTrendChart()
    } else {
      proxy.$message.error(response.message || '获取出库趋势数据失败')
    }
  } catch (error) {
    console.error('获取出库趋势数据失败:', error)
  }
}

// 渲染入库趋势图表
const renderInboundTrendChart = () => {
  if (!inboundTrendChartInstance) {
    inboundTrendChartInstance = echarts.init(document.getElementById('inboundTrendChart'))
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['数量', '金额'],
      top: 10,
      right: 20
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: inboundTrendData.value.dates,
      axisPointer: {
        type: 'shadow'
      },
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '金额',
        position: 'right',
        axisLabel: {
          formatter: '¥{value}'
        }
      }
    ],
    series: [
      {
        name: '数量',
        type: 'bar',
        data: inboundTrendData.value.quantities,
        itemStyle: {
          color: '#5470c6'
        },
        barWidth: '40%'
      },
      {
        name: '金额',
        type: 'line',
        yAxisIndex: 1,
        data: inboundTrendData.value.amounts,
        itemStyle: {
          color: '#91cc75'
        },
        smooth: true,
        symbolSize: 6
      }
    ]
  }
  
  inboundTrendChartInstance.setOption(option)
}

// 渲染出库趋势图表
const renderOutboundTrendChart = () => {
  if (!outboundTrendChartInstance) {
    outboundTrendChartInstance = echarts.init(document.getElementById('outboundTrendChart'))
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['数量', '金额'],
      top: 10,
      right: 20
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: outboundTrendData.value.dates,
      axisPointer: {
        type: 'shadow'
      },
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '金额',
        position: 'right',
        axisLabel: {
          formatter: '¥{value}'
        }
      }
    ],
    series: [
      {
        name: '数量',
        type: 'bar',
        data: outboundTrendData.value.quantities,
        itemStyle: {
          color: '#fac858'
        },
        barWidth: '40%'
      },
      {
        name: '金额',
        type: 'line',
        yAxisIndex: 1,
        data: outboundTrendData.value.amounts,
        itemStyle: {
          color: '#91cc75'
        },
        smooth: true,
        symbolSize: 6
      }
    ]
  }
  
  outboundTrendChartInstance.setOption(option)
}

// 获取入库排名数据
const loadInboundRanking = async () => {
  try {
    const response = await http.get('api/Dashboard/GetInboundRanking', { topN: 10, days: 30 })
    
    if (response.success) {
      inboundRankingData.value = response.data || []
    } else {
      proxy.$message.error(response.message || '获取入库排名数据失败')
    }
  } catch (error) {
    console.error('获取入库排名数据失败:', error)
  }
}

// 获取出库排名数据
const loadOutboundRanking = async () => {
  try {
    const response = await http.get('api/Dashboard/GetOutboundRanking', { topN: 10, days: 30 })
    
    if (response.success) {
      outboundRankingData.value = response.data || []
    } else {
      proxy.$message.error(response.message || '获取出库排名数据失败')
    }
  } catch (error) {
    console.error('获取出库排名数据失败:', error)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (quantityChartInstance) {
    quantityChartInstance.resize()
  }
  if (amountChartInstance) {
    amountChartInstance.resize()
  }
  if (inboundTrendChartInstance) {
    inboundTrendChartInstance.resize()
  }
  if (outboundTrendChartInstance) {
    outboundTrendChartInstance.resize()
  }
}

onMounted(() => {
  // 初始加载数据
  getDashboardData()
  loadInboundTrend()
  loadOutboundTrend()
  loadInboundRanking()
  loadOutboundRanking()
  
  // 设置定时刷新（60秒）
  refreshInterval = setInterval(() => {
    getDashboardData()
    loadInboundTrend()
    loadOutboundTrend()
    loadInboundRanking()
    loadOutboundRanking()
  }, 60000)
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清除定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
  
  // 销毁图表实例
  if (quantityChartInstance) {
    quantityChartInstance.dispose()
  }
  if (amountChartInstance) {
    amountChartInstance.dispose()
  }
  if (inboundTrendChartInstance) {
    inboundTrendChartInstance.dispose()
  }
  if (outboundTrendChartInstance) {
    outboundTrendChartInstance.dispose()
  }
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="less" scoped>
.dashboard-container {
  position: absolute;
  height: 100vh;
  width: 100%;
  background: #f3f7fb;
}

.dashboard-content {
  padding: 20px;
  min-height: 100vh;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.overview-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
  margin-bottom: 30px;
}

.overview-item {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  position: relative;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .overview-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
  }

  .overview-value {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
  }

  .action-btn {
    position: absolute;
    top: 15px;
    right: 15px;
  }
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-box {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  text-align: center;
}

.chart {
  height: 400px;
  width: 100%;
}

.trend-section {
  margin-top: 20px;
}

.trend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.time-range-tabs {
  display: flex;
  align-items: center;
}

.trend-chart {
  height: 350px;
  width: 100%;
}

.ranking-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.ranking-box {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ranking-table-wrapper {
  overflow-x: auto;
  margin-top: 15px;
}

.ranking-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;

  thead {
    background: #f5f7fa;

    th {
      padding: 12px 8px;
      text-align: left;
      font-weight: 600;
      color: #333;
      border-bottom: 2px solid #e4e7ed;
    }
  }

  tbody {
    tr {
      transition: background-color 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      &:not(:last-child) {
        border-bottom: 1px solid #ebeef5;
      }
    }

    td {
      padding: 12px 8px;
      color: #606266;
    }
  }

  .goods-name {
    font-weight: 500;
    color: #333;
  }

  .text-right {
    text-align: right;
  }

  .text-center {
    text-align: center;
  }

  .empty-data {
    text-align: center;
    color: #909399;
    padding: 40px 0;
  }
}

.rank-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  font-weight: bold;
  font-size: 14px;
  background: #f0f2f5;
  color: #666;

  &.rank-first {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
  }

  &.rank-second {
    background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
    color: #fff;
    box-shadow: 0 2px 8px rgba(253, 160, 133, 0.4);
  }

  &.rank-third {
    background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
    color: #fff;
    box-shadow: 0 2px 8px rgba(166, 193, 238, 0.4);
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .ranking-container {
    grid-template-columns: 1fr;
  }
}


</style>
